import React, { PureComponent } from 'react';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Card, Button, Col, Row, Input, Select, message, Modal, Tooltip } from 'antd';
import { connect } from 'dva';
import router from 'umi/router';
import FooterToolbar from '@/components/FooterToolbar';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import HOCSelect from '@/components/AntDesign/Select';
import Area from '../../components/Area';

const { Option } = Select;
const { TextArea } = Input;
const FormItem = Form.Item;

@connect(({ login, waresave }) => ({
  login,
  waresave,
}))
@Form.create()
class AccuWareAdd extends PureComponent {
  state = {
    supplyList: [],
    updateDis: false,
    YES_NO_FLAG: [],
    comList: [],
    proFundListFlag: false,
    sysCode: 1,
  };

  componentDidMount() {
    const { login, dispatch, form } = this.props;
    const { userType } = login.baseUser;
    this.setState({ comDis: +userType !== 1 });
    const { systemList } = login;
    const { sysCode } = systemList.filter(item => item.isSelected)[0];
    this.setState({
      sysCode,
    });
    dispatch({
      type: 'publicdata/fetchDictCode',
      payload: ['YES_NO_FLAG'],
    }).then(res => {
      this.setState({ YES_NO_FLAG: res.YES_NO_FLAG }); // 页签
    });

    // 获取企业信息
    dispatch({
      type: 'waresave/fetchAccuCorpList',
      payload: {},
    }).then(res => {
      if (+userType === 1) {
        this.setState({ comList: res.data });
        // 查询负责人列表
        this.getRespList();
      } else {
        this.getRespList(res.data[0].corpId);
        form.setFieldsValue({
          uniCreditCode: res.data[0].uniCreditCode,
          unitName: res.data[0].companyName,
        });
        this.setState({ corpId: res.data[0].corpId, unitName: res.data[0].companyName });
      }
    });
  }

  // 查询负责人列表
  getRespList = corpId => {
    const { dispatch } = this.props;
    dispatch({
      type: 'waresave/fetchUserId',
      payload: {
        corpId,
      },
    });
  };

  // 取消
  cancel = () => {
    router.goBack();
  };

  // 提交并启用
  modalOk = () => {
    const { insertVlues } = this.state;
    this.setState({
      submitStartLoading: true,
    });
    const { dispatch } = this.props;
    dispatch({
      type: 'waresave/fetchInsertStart',
      payload: insertVlues,
    }).then(res => {
      if (res.success) {
        this.setState({
          visible: false,
        });
        router.goBack();
      } else {
        message.warning(res.message);
      }
      this.setState({
        submitStartLoading: false,
      });
    });
  };

  onCancel = () => {
    this.setState({
      visible: false,
    });
  };

  showModal = () => {
    const { form } = this.props;
    const { selectedAreaId, unitName, corpId } = this.state;
    form.validateFieldsAndScroll((err, values) => {
      const newValue = values;
      if (!err) {
        Object.keys(values).forEach(key => {
          if (key === 'areaId') {
            newValue[key] = selectedAreaId;
          } else if (key === 'unitName') {
            newValue[key] = unitName;
          }
        });
        newValue.unitId = corpId;
        this.setState({
          visible: true,
          insertVlues: newValue,
        });
      }
    });
  };

  insert = obj => {
    this.setState({
      submitLoading: true,
    });
    const { dispatch } = this.props;
    dispatch({
      type: 'waresave/fetchInsert',
      payload: obj,
    }).then(res => {
      if (res.success) {
        router.goBack();
      } else {
        message.warning(res.message);
      }
      this.setState({
        submitLoading: false,
      });
    });
  };

  // 申报负责人备注内容
  renderRepListTip = () => (
    <Tooltip
      placement="right"
      title="只可以选择具有社保公积金系统权限的人员，只有设置的人员可查看该大库的增减员申报信息。"
    >
      <span>申报负责人</span>
      <ExclamationCircleOutlined style={{ marginLeft: 5 }} />
    </Tooltip>
  );

  // 表单检测 并 提交
  submitAll = () => {
    const { unitName, corpId, selectedAreaId } = this.state;
    const { form } = this.props;
    form.validateFieldsAndScroll((err, values) => {
      const newValues = values;
      if (!err) {
        Object.keys(values).forEach(key => {
          if (key === 'areaId') {
            newValues[key] = selectedAreaId;
          }
          if (key === 'unitName') {
            newValues[key] = unitName;
          }
        });
        newValues.unitId = corpId;
        this.insert({ ...newValues, accoStatus: 1, corpId });
      }
    });
  };

  getData = (value, id) => {
    const { form } = this.props;
    const tempAreaId = value.key;
    this.setState({ selectedAreaId: tempAreaId });
    this.getproFundList(tempAreaId);
    form.setFieldsValue({ [id]: { key: tempAreaId } });
  };

  // 运行政策名称（公积金组）
  getproFundList = areaId => {
    const { dispatch, form } = this.props;
    const { proFundListFlag } = this.state;
    // 获取企业信息
    dispatch({
      type: 'waresave/fetchAccuLsPkg',
      payload: { areaId },
    }).then(res => {
      if (res.success) {
        this.setState({
          supplyList: res.data || [],
        });
      }
      if (proFundListFlag) {
        form.setFieldsValue({
          accuLsPkgIdsList: [],
        });
      }
      this.setState({
        proFundListFlag: true,
      });
    });
  };

  comInfoChange = value => {
    const { comList } = this.state;
    const { form } = this.props;
    comList.map(item => {
      if (String(item.corpId) === String(value)) {
        form.setFieldsValue({
          uniCreditCode: item.uniCreditCode,
        });
        this.setState({
          corpId: item.corpId,
          unitName: item.companyName,
        });
        this.getRespList(item.corpId);
      }
      return true;
    });
  };

  // 渲染函数
  render() {
    const { form, waresave } = this.props;
    const { getFieldDecorator } = form;
    const {
      YES_NO_FLAG,
      comList,
      comDis,
      updateDis,
      supplyList,
      visible,
      sysCode,
      submitLoading,
      submitStartLoading,
    } = this.state;
    const dictOL = dictList =>
      dictList.map(options => <Option key={options.itemCode}>{options.itemName}</Option>);

    const comOption = comList.map(value => (
      <Option key={value.corpId} value={value.corpId}>
        {value.companyName}
      </Option>
    ));
    return (
      <Form layout="vertical">
        <PageHeaderWrapper>
          <Card title={<span>公积金账户信息</span>} bordered={false}>
            <Row gutter={64}>
              <Col xl={{ span: 8 }} lg={{ span: 8 }} md={{ span: 8 }} sm={24}>
                <FormItem label="大库名称">
                  {getFieldDecorator('accoName', {
                    rules: [{ required: true, pattern:/^(?!\.)[^\\/:*?"<>|]{1,255}$/,message: '文件名不能包含下列任何字符  \\  /  :  *   ?  "  <  >  |'}],
                  })(<Input placeholder="请输入大库名称" maxLength={50} />)}
                </FormItem>
              </Col>
              <Col xl={{ span: 8 }} lg={{ span: 8 }} md={{ span: 8 }} sm={24}>
                <FormItem label="公司名称">
                  {getFieldDecorator('unitName', {
                    rules: [{ required: true, message: '请选择公司名称' }],
                  })(
                    comList.length ? (
                      <HOCSelect
                        allowClear
                        showSearch
                        filterOption={(input, option) =>
                          option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                        }
                        placeholder="请输入公司名称"
                        onChange={this.comInfoChange}
                      >
                        {comOption}
                      </HOCSelect>
                    ) : (
                      <Input placeholder="请输入公司名称" disabled={comDis} />
                    )
                  )}
                </FormItem>
              </Col>
              <Col xl={{ span: 8 }} lg={{ span: 8 }} md={{ span: 8 }} sm={24}>
                <FormItem label="统一社会信用代码">
                  {getFieldDecorator('uniCreditCode', {
                    rules: [{ required: true, message: '请输入统一社会信用代码' }],
                  })(<Input placeholder="请输入统一社会信用代码" disabled />)}
                </FormItem>
              </Col>
            </Row>
            <Row gutter={64}>
              <Col xl={{ span: 8 }} lg={{ span: 8 }} md={{ span: 8 }} sm={24}>
                <FormItem label="开户地区">
                  {getFieldDecorator('areaId', {
                    rules: [{ required: true, message: '请选择开户地区' }],
                  })(<Area labelInValue onChange={value => this.getData(value, 'areaId')} />)}
                </FormItem>
              </Col>
              <Col xl={{ span: 8 }} lg={{ span: 8 }} md={{ span: 8 }} sm={24}>
                <FormItem label="所属公积金机构">
                  {getFieldDecorator('blngAccoOrg', {
                    rules: [{ required: true, message: '请输入所属公积金机构' }],
                  })(<Input placeholder="请输入所属公积金机构" maxLength={50} />)}
                </FormItem>
              </Col>
              <Col xl={{ span: 8 }} lg={{ span: 8 }} md={{ span: 8 }} sm={24}>
                <FormItem label="是否可突破上限">
                  {getFieldDecorator('isExceedCeiling', {
                    rules: [{ required: false, message: '请选择是否可突破上限' }],
                    initialValue: '2',
                  })(
                    <HOCSelect
                      allowClear
                      showSearch
                      filterOption={(input, option) =>
                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                      }
                      placeholder="请选择是否可突破上限"
                    >
                      {dictOL(YES_NO_FLAG)}
                    </HOCSelect>
                  )}
                </FormItem>
              </Col>
            </Row>

            <Row gutter={64}>
              <Col xl={{ span: 8 }} lg={{ span: 8 }} md={{ span: 8 }} sm={24}>
                <FormItem
                  label={
                    <span>
                      公积金组<span style={{ color: '#999999' }}>(可多选)</span>
                    </span>
                  }
                >
                  {getFieldDecorator('accuLsPkgIdsList', {
                    rules: [{ required: true, message: '请选择公积金组（可多选）' }],
                  })(
                    <HOCSelect
                      allowClear
                      showSearch
                      filterOption={(input, option) =>
                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                      }
                      onChange={this.paywayChange}
                      placeholder="请选择本大库支持的政策名称"
                      mode="multiple"
                      disabled={updateDis}
                    >
                      {supplyList.map(value => (
                        <Option key={value.accuLsPkgId} value={value.accuLsPkgId}>
                          {value.accuLsPkgName}
                        </Option>
                      ))}
                    </HOCSelect>
                  )}
                </FormItem>
              </Col>
              <Col xl={{ span: 8 }} lg={{ span: 8 }} md={{ span: 8 }} sm={24}>
                <FormItem label="开户行">
                  {getFieldDecorator('custBankName', {
                    rules: [{ required: false, message: '请输入开户行' }],
                  })(<Input placeholder="请输入开户行" maxLength={50} />)}
                </FormItem>
              </Col>
              <Col xl={{ span: 8 }} lg={8} md={8} sm={24}>
                <FormItem label="银行账号">
                  {getFieldDecorator('custBankId', {
                    rules: [
                      { required: false, message: '最大长度不超过25位数字', pattern: /^\d{1,25}$/ },
                    ],
                  })(<Input placeholder="请输入银行账号" maxLength={25} />)}
                </FormItem>
              </Col>
            </Row>
            <Row gutter={64}>
              {Number(sysCode) !== 2 && (
                <Col xl={{ span: 8 }} lg={{ span: 8 }} md={{ span: 8 }} sm={24}>
                  <FormItem label={this.renderRepListTip()}>
                    {getFieldDecorator('respList', {
                      rules: [{ required: true, message: '请选择申报负责人' }],
                    })(
                      <HOCSelect
                        allowClear
                        showSearch
                        filterOption={(input, option) =>
                          option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                        }
                        mode="multiple"
                        style={{ width: '100%' }}
                        placeholder="请选择"
                      >
                        {waresave.respDataList.map(value => (
                          <Option key={value.userId} value={value.userId}>
                            {value.userName}
                          </Option>
                        ))}
                      </HOCSelect>
                    )}
                  </FormItem>
                </Col>
              )}
              <Col xl={{ span: 8 }} lg={8} md={8} sm={24}>
                <FormItem label="备注">
                  {getFieldDecorator('remark', {})(
                    <TextArea placeholder="请输入备注" maxLength={100} />
                  )}
                </FormItem>
              </Col>
            </Row>
          </Card>
          <Modal
            title="提醒"
            visible={visible}
            onOk={this.modalOk}
            onCancel={this.onCancel}
            confirmLoading={submitStartLoading}
            okText="继续"
            cancelText="取消"
          >
            <p>
              大库启用后，【公司名称】、【统一社会信用代码】、【开户地区】、【是否可突破上限】、【公积金组合】将不可修改，请确认是否继续？
            </p>
          </Modal>

          <FooterToolbar>
            <Button onClick={this.cancel}> 取消 </Button>
            <Button type="primary" onClick={this.submitAll} loading={submitLoading}>
              提交
            </Button>
            <Button type="primary" onClick={this.showModal}>
              提交并启用
            </Button>
          </FooterToolbar>
        </PageHeaderWrapper>
      </Form>
    );
  }
}

export default AccuWareAdd;
